package com.bonc.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Api(value = "R模块Sign服务")
@RestController
public class SignUtil {

    @Autowired
    ObjectMapper jsonMapper;

    @ApiOperation(value = "转换签名", notes = "脱机版，根据请求报文转换成sign string ,请求格式为content-type/json，Http header需要有APP_SECERT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appId", value = "请求机构App Id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "APP_SECRET", value = "请求机构App Secret", required = true, dataType = "String") })
    @RequestMapping(value = "/api/sign/mapper", method = RequestMethod.POST)
    public String sign(HttpServletRequest request) throws Exception {
        String appSecret = request.getHeader("APP_SECRET");
        String queryjson = IOUtils.toString(request.getInputStream(), Charset.forName("utf-8"));
        Map<String, String> maps = jsonMapper.readValue(queryjson, Map.class);
        String requestSignString = getRequestRelatedStrings(maps);
        //String originalString = appSecret + requestSignString + appSecret;
        String test = "r1v7w0E84jaccessToken20211117095520735cf2c65cde4a4bbaff6845f83086b0-0057-1634522120busTypeCSVCcontent{\"CreatorContactInfo\":\"17710116707\",\"CreatTime\":\"20211023151853\",\"Title\":\"测试\",\"OriginUnit\":\"0057\",\"Creator\":\"郑勇键\",\"IdentySubtype\":\"0001\",\"Identifier\":\"20211023GZL00571852997\",\"Content\":\"测试内容\",\"IdentyType\":\"00\",\"ReceiverUnit\":\"351\"}cutOffDay20211023domainCSVBenvFlag0routeType00routeValue351sessionID2021102315185429601701001signMethodmd5timeStamp20211023151854transIDO2021102315185429601701001version1.0.1r1v7w0E84j";
        return checkMD5(test);
    }

    // only utf-8 supported
    public static String checkMD5(String originalString)
            throws UnsupportedEncodingException, NoSuchAlgorithmException, IllegalArgumentException {
        byte[] signedOriginalStringBytes = MessageDigest.getInstance("MD5").digest(originalString.getBytes("UTF-8"));
        String signedOriginalString = new HexBinaryAdapter().marshal(signedOriginalStringBytes);
        System.out.println(signedOriginalString);
        return signedOriginalString;
    }



    protected String getRequestRelatedStrings(Map<String, String> parameterMap) {
        Set<String> parameterMapKeySet = parameterMap.keySet();
        String[] parameterMapKeySetArray = parameterMapKeySet.toArray(new String[parameterMapKeySet.size()]);
        Arrays.sort(parameterMapKeySetArray);
        StringBuilder requestSignStringBuilder = new StringBuilder();
        for (int i = 0; i < parameterMapKeySetArray.length; i++) {
            String key = parameterMapKeySetArray[i];
            String value = getNonNull(parameterMap.get(key));
            if (!"sign".equals(key))
                requestSignStringBuilder.append(key).append(value);
        }
        return requestSignStringBuilder.toString();

    }

    String getNonNull(String string)
    {
        return string == null ? "" : string;
    }

    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String test = "r1v7w0E84jaccessToken20211117095520735cf2c65cde4a4bbaff6845f83086b0-0057-1634522120busTypeCSVCcontent{\\\"CreatorContactInfo\\\":\\\"17710116707\\\",\\\"CreatTime\\\":\\\"20211023144731\\\",\\\"Title\\\":\\\"测试\\\",\\\"OriginUnit\\\":\\\"0057\\\",\\\"Creator\\\":\\\"郑勇键\\\",\\\"IdentySubtype\\\":\\\"0001\\\",\\\"Identifier\\\":\\\"20211023GZL00574730763\\\",\\\"Content\\\":\\\"测试内容\\\",\\\"IdentyType\\\":\\\"00\\\",\\\"ReceiverUnit\\\":\\\"351\\\"}cutOffDay20211023domainCSVBenvFlag0routeType00routeValue351sessionID2021102314473122101701001signMethodmd5timeStamp20211023144731transIDO2021102314473122101701001version1.0.1r1v7w0E84j";
        System.out.println(SignUtil.checkMD5(test));
    }
}
